package admin

import (
	"crypto/sha256"
	"fmt"
	"goProject/api/auth"
	"goProject/db"
	"goProject/table"
	"net/http"
	"strconv"
	"time"

	"gitee.com/ruige_fun/util/rlog"

	"gitee.com/ruige_fun/util/std"
	"github.com/kataras/iris/v12"
)

// getCodeList 获取全部的注册码
func getCodeList(c iris.Context) {
	var result = make([]table.RegisterCode, 0)
	db.MySQL.Preload("Role").Order("`id` DESC").Find(&result)
	c.JSON(std.NewResp(http.StatusOK, "", result, nil))
}

type pCreateCode struct {
	RoleID uint `json:"role_id" validate:"required,min=1"`
}

// createCode 创建新的注册码
func createCode(c iris.Context) {
	var p pCreateCode
	err := c.ReadJSON(&p)
	if err != nil {
		c.JSON(std.NewResp(http.StatusBadRequest, "参数校验失败", nil, nil))
		return
	}
	myID, _ := strconv.Atoi(fmt.Sprint(c.GetID()))
	if myID != 1 {
		roleID, _ := auth.Role.Get(fmt.Sprint(c.GetID())) //获取自己的权限ID
		if p.RoleID <= uint(roleID) {
			c.JSON(std.NewResp(http.StatusBadRequest, "无法创建比自己权限高或者同等权限的账号", nil, nil))
			return
		}
	}
	db.MySQL.Create(&table.RegisterCode{
		RoleID:    p.RoleID,
		Code:      fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint(time.Now())))),
		CmdUserID: uint(myID),
	})
	rlog.Success("创建注册码：用户", myID, "创建了权限为", p.RoleID, "的注册码。")
	c.JSON(std.NewResp(http.StatusOK, "", nil, nil))
}

type pDeleteCode struct {
	ID uint `json:"id" validate:"required,min=2"`
}

func deleteCode(c iris.Context) {
	var p pDeleteCode
	err := c.ReadQuery(&p)
	if err != nil {
		c.JSON(std.NewResp(http.StatusBadRequest, "参数校验失败", nil, nil))
		return
	}
	var code table.RegisterCode
	db.MySQL.Where("`id` = ?", p.ID).First(&code)
	if code.ID <= 0 {
		c.JSON(std.NewResp(http.StatusBadRequest, "删除失败，指定code已不存在", nil, nil))
		return
	}
	if code.UserID > 0 {
		c.JSON(std.NewResp(http.StatusBadRequest, fmt.Sprintf("删除失败，指定code已被用户【%v】注册", code.UserID), nil, nil))
		return
	}
	db.MySQL.Where("`id` = ?", code.ID).Delete(&table.RegisterCode{})
	c.JSON(std.NewResp(http.StatusOK, "", nil, nil))
}
